<!-- 标签管理 - 工程数据管理 - 标签模板配置 -->
<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      v-model="form"
      :page.sync="page"
      :search.sync="query"
      :permission="permissionList"
      :before-open="beforeOpen"
      ref="crud"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <template slot="menuLeft">
        <el-button type="primary" size="small" icon="el-icon-plus" @click="openPrintLabelModal">新 增 </el-button>
        <el-button type="danger" size="small" icon="el-icon-delete" @click="handleDelete">删 除 </el-button>
        <el-button type="danger" size="small" icon="el-icon-delete" @click="dataUnbinding">数据源解绑 </el-button>
        <el-button type="primary" size="small" @click="defaultSCM">默认SCM模板</el-button>
      </template>
      <template slot="subTypeSearch">
        <el-select v-model="query.subType" placeholder="请选择业务小类" :clearable="true">
          <el-option v-for="cateItem in subTypeList" :key="cateItem.value" :label="cateItem.label" :value="cateItem.value"> </el-option>
        </el-select>
      </template>
      <template slot="menuRight">
        <user-table-config :option="option" @confirm="(val) => handleSetUserConfig(val, pageCode)"></user-table-config>
      </template>
      <template slot-scope="{ row, index }" slot="menu">
        <!--        <el-button v-if="permission.labeltemplate_view" icon="el-icon-view" size="small" type="text" @click="rowView(row)">查看</el-button>-->
        <el-button icon="el-icon-edit" size="small" type="text" @click.stop="openUpdate(row)">编辑</el-button>
        <el-button icon="el-icon-download" size="small" type="text" @click.stop="openDownload(row)">下载</el-button>
        <el-button icon="el-icon-delete" size="small" type="text" @click="$refs.crud.rowDel(row, index)">删除</el-button>
        <el-button size="small" type="text" icon="el-icon-paperclip" @click="selectItem(row, 'config')">绑定数据源</el-button>
        <el-button size="small" type="text" icon="el-icon-top" @click="templateApplication(row)">版本管理</el-button>
      </template>
    </avue-crud>
    <el-dialog append-to-body :title="dialogTitle" :visible.sync="printLabelModal" @close="closeDialog" class="labeltemplateDialog">
      <div class="sail-header-dialog-content">
        <avue-form ref="printLabelForm" v-model="form" v-if="printLabelModal" :option="printLabelOption" :upload-before="uploadBefore" :upload-after="uploadAfter">
          <template slot="code">
            <el-input placeholder="请输入编码" v-model="form.code">
              <el-button slot="append" icon="el-icon-refresh-right" @click="updateCode"></el-button>
            </el-input>
          </template>
        </avue-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button v-if="dialogTitle === '新增'" size="small" type="primary" @click="onSavePrintLabel"><i class="el-icon-circle-plus-outline"></i><span>保 存</span></el-button>
        <el-button v-if="dialogTitle === '编辑'" size="small" type="primary" @click="onSavePrintLabel"><i class="el-icon-circle-check"></i><span>修 改</span></el-button>
        <el-button v-if="dialogTitle !== '查看'" size="small" @click="printLabelModal = false"><i class="el-icon-circle-close"></i><span>取 消</span></el-button>
      </span>
    </el-dialog>
    <!--选择绑定数据源弹出框-->
    <el-dialog title="选择数据源" top="5vh" append-to-body :visible.sync="showCheckDialog" width="70%">
      <div class="sail-header-dialog-content">
        <avue-crud
          :option="itemOption"
          :table-loading="loading"
          :data="dataValue"
          :page.sync="page"
          :permission="permissionList"
          v-model="itemObj"
          ref="inspectionProperties"
          @current-change="currentItemChange"
          @size-change="sizeItemChange"
          @search-change="searchItemChange"
          @search-reset="searchItemReset"
          @on-load="onLoadpage"
          @row-click="rowClick"
        >
          <template slot="radio" slot-scope="{ row }">
            <el-radio v-model="selectionid" :label="row.id">
              <span></span>
            </el-radio>
          </template>
          <template slot="index" slot-scope="{ row }">
            <span> {{ row.$index + 1 }}</span>
          </template>
        </avue-crud>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" type="primary" @click="dataBinding"><i class="el-icon-circle-plus-outline"></i><span>绑定</span></el-button>
        <el-button size="small" @click="showCheckDialog = false"><i class="el-icon-circle-close"></i><span>取 消</span></el-button>
      </span>
    </el-dialog>
    <!--版本管理-->
    <el-dialog title="版本管理" append-to-body :visible.sync="showedition" width="70%" top="5vh">
      <avue-crud
        :option="optionedition"
        :table-loading="loading"
        :data="dataedition"
        :page.sync="editionpage"
        :before-open="beforeOpen"
        ref="crudedition"
        @row-update="rowUpdateEdition"
        @row-save="rowSaveEdition"
        @row-del="rowDelEdition"
        @search-change="searchChangeTO"
        @search-reset="searchResetTO"
        @selection-change="selectionChange"
        @current-change="currentChange"
        @size-change="sizeChange"
        @refresh-change="refreshChangeTo"
        :upload-after="uploadAfter"
      >
      </avue-crud>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="showedition = false"><i class="el-icon-circle-close"></i><span>取 消</span></el-button>
      </span>
    </el-dialog>
    <!-- 默认SCM模板 -->
    <el-dialog title="默认SCM模板" append-to-body :visible.sync="defaultScmDialog.visible" width="30%">
      <avue-form ref="defaultScmDialogForm" :option="defaultScmDialog.option" v-model="defaultScmDialog.form" @submit="defaultScmDialogSubmit"> </avue-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" icon="el-icon-circle-close" @click="defaultScmDialog.visible = false">取消</el-button>
        <el-button size="small" type="primary" icon="el-icon-check" @click="$refs.defaultScmDialogForm.submit()">提交</el-button>
      </span>
    </el-dialog>
    <common-modal-template ref="commonModalTemplate" :option="tableOption" @getSelectedRows="getSelectedRows" :key="timer" @newKey="newKey"></common-modal-template>
  </basic-container>
</template>

<script>
import { getList, getDetail, add, update, remove, bindingDataSql, unBindingDataSql, addinfo, setDefaultScm, getScmDefault } from '@/api/admin/labeltemplate';
import { getPage } from '@/api/labelManagement/tagDataSource';
import { mapGetters } from 'vuex';
import { guid } from '@/util/helpers';
import { downloadFileByUrl } from '@/util/util';
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template.vue';
import userTableConfig from '@/components/user-table-config';
import userConfig from '@/mixins/userConfig';
import { getCategory } from '@/api/warehouse/materialRules';
import { over } from 'stompjs';
export default {
  name: 'AdminLabeltemplate',
  components: {
    CommonModalTemplate,
    userTableConfig
  },
  mixins: [userConfig()],
  inject: ['globalStartLoad', 'globalEndLoad'],
  data() {
    return {
      pageCode: 'ADMIN_LABEL_TEMPLATE',
      fileName: '',
      form: {},
      query: {},
      loading: true,
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      dataId: '',
      selectionInfo: '',
      selectionList: [],
      subTypeList: [],
      option: {
        height: 'calc(100vh - 412px)',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 24,
        searchMenuPosition: 'right',
        menuWidth: 420,
        border: true,
        index: true,
        addBtn: false,
        viewBtn: true,
        viewBtnText: '详情',
        viewTitle: '详情',
        editBtn: false,
        delBtn: false,
        selection: true,
        dialogClickModal: false,
        indexLabel: '序号',
        columnBtn: false,
        labelWidth: 200,
        column: [
          {
            label: '大类',
            prop: 'type',
            type: 'select',
            dicUrl: '/api/blade-system/dict/dictionary?code=serial',
            cascader: ['subType'],
            props: {
              label: 'dictValue',
              value: 'dictKey'
            },
            change: ({ column, value }) => {
              this.getSubTypeData(value);
            },
            search: true
          },
          {
            label: '小类',
            prop: 'subType',
            // dicUrl: '/api/blade-system/dict/dictionary?code={{key}}',
            // props: {
            //   label: 'dictValue',
            //   value: 'dictKey'
            // },
            formatter: (row) => {
              const subTypeMap = {
                WORKORDER: '工单',
                FLOW_CARD: '流程卡',
                WAREHOUSE: '仓库',
                WORKSTATION: '产线（工位）',
                STORAGE_AREA: '存储区域',
                EQUIPEMENT: '设备及其属性',
                TOOL: '工装/夹具',
                VEHICLE: '载具',
                INSPECTION_RESULTS: '检验结果',
                FAULT_PHENOMENON: '故障现象/故障类别',
                RAW_MATERIAL_PACKAGING: '原材料包装',
                WORK_IN_PROGRESS: '在制品',
                FINISHED_PRODUCT_PACKAGING: '成品包装',
                ACCESSORIES: '辅料',
                PALLET: '栈板',
                SCM_DO: 'SCM送货单',
                NG: '故障'
              };
              return subTypeMap[row.subType] || '';
            },
            fromslot: true,
            type: 'select',
            search: true
          },
          {
            label: '模板名称',
            prop: 'name',
            search: true
          },
          {
            label: '模板代码',
            prop: 'code',
            search: true
          },
          {
            label: '版本名称',
            prop: 'version'
          },
          {
            label: '缩略图',
            prop: 'thumbnailUrl',
            type: 'upload',
            loadText: '缩略图上传中，请稍等',
            propsHttp: {
              url: 'link',
              name: 'originalName',
              res: 'data'
            },
            listType: 'picture',
            limit: 1,
            accept: 'image/png, image/jpeg, image/jpg',
            tip: '只能上传png/jpeg/jpg文件',
            action: '/api/blade-resource/oss/endpoint/put-file-attach'
          },
          {
            label: '标签地址',
            prop: 'fileUrl'
          },
          {
            label: '数据源',
            prop: 'placeholderDataName'
          },
          {
            label: '打印列数',
            prop: 'columnCount'
          },
          {
            label: '打印份数',
            prop: 'copies'
          },
          {
            label: '创建人',
            prop: 'createUserName'
          },
          {
            label: '生成日期',
            prop: 'createTime'
          },
          {
            label: '最后修改人',
            prop: 'updateUserName'
          },
          {
            label: '最后修改日期',
            prop: 'updateTime'
          },
          {
            label: '备注',
            prop: 'remark'
          }
        ]
      },
      printLabelModal: false,
      dialogTitle: '新增',
      printLabelOption: {
        submitBtn: false,
        emptyBtn: false,
        labelWidth: 125,
        column: [
          {
            label: '大类',
            prop: 'type',
            type: 'select',
            dicUrl: '/api/blade-system/dict/dictionary?code=serial',
            cascader: ['subType'],
            props: {
              label: 'dictValue',
              value: 'dictKey'
            },
            search: true
          },
          {
            label: '小类',
            prop: 'subType',
            dicUrl: '/api/blade-system/dict/dictionary?code={{key}}',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            },
            type: 'select',
            search: true
          },
          {
            label: '模板名称',
            prop: 'name',
            rules: [
              {
                required: true,
                message: '请输入模板名称',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '代码',
            prop: 'code',
            rules: [
              {
                required: true,
                message: '请输入代码',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '打印列数',
            prop: 'columnCount',
            type: 'number',
            precision: 0,
            minRows: 1,
            value: 1,
            rules: [
              {
                required: true,
                message: '请输入打印列数',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '打印份数',
            prop: 'copies',
            type: 'number',
            precision: 0,
            minRows: 1,
            value: 1,
            rules: [
              {
                required: true,
                message: '请输入打印份数',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '备注',
            prop: 'remark'
          },

          {
            label: '上传缩略图',
            prop: 'thumbnailUrl',
            type: 'upload',
            loadText: '缩略图上传中，请稍等',
            propsHttp: {
              url: 'link',
              name: 'originalName',
              res: 'data'
            },
            listType: 'picture',
            limit: 1,
            accept: 'image/png, image/jpeg, image/jpg',
            tip: '只能上传png/jpeg/jpg文件',
            action: '/api/blade-resource/oss/endpoint/put-file-attach'
          },
          {
            label: '上传打印标签',
            prop: 'fileUrl',
            type: 'upload',
            loadText: '标签上传中，请稍等',
            propsHttp: {
              url: 'link',
              name: 'originalName',
              res: 'data'
            },
            listType: 'text',
            limit: 1,
            accept: '.btw',
            tip: '只能上传btw文件',
            action: '/api/blade-resource/oss/endpoint/put-file-attach',
            rules: [
              {
                required: true,
                message: '请上传打印标签',
                trigger: 'blur'
              }
            ]
          }
          // {
          //     label: "大小",
          //     prop: "size",
          //     rules: [{
          //         required: true,
          //         message: "请输入 大小",
          //         trigger: "blur"
          //     }]
          // },
          // {
          //     label: "资料库名称",
          //     prop: "repoName",
          //     rules: [{
          //         required: true,
          //         message: "请输入 资料库名称",
          //         trigger: "blur"
          //     }]
          // }
        ]
      },
      data: [],
      dataValue: [],
      tableOption: {}, //公用模态框配置信息
      showCheckDialog: false, //展示选择dialog
      //绑定数据弹出框数据
      labelTemplateIds: '',
      selectionid: '',
      itemPage: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      itemObj: {},
      itemData: [], //检验项明细列表
      itemOption: {
        height: 500,
        tip: false,
        menu: false,
        addBtn: false,
        searchShow: true,
        searchSpan: 5,
        searchMenuSpan: 4,
        labelWidth: 110,
        dialogCustomClass: 'custom-class',
        border: true,
        index: false,
        indexLabel: '序号',
        refreshBtn: true,
        excelBtn: false,
        selection: false,
        dialogDrag: false, // 开启拖拽功能
        dialogClickModal: false,
        columnBtn: true,
        column: [
          {
            label: '',
            prop: 'radio',
            width: 60,
            hide: false
          },
          {
            label: '序号',
            prop: 'index',
            width: 60,
            hide: false
          },
          {
            label: '数据名称',
            prop: 'name',
            search: true,
            maxlength: 30,
            rules: [
              {
                required: true,
                message: '请输入数据名称',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '数据编码',
            prop: 'code',
            rules: [
              {
                required: true,
                message: '请输入数据编码',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '数据描述',
            prop: 'remark',
            rules: [
              {
                required: true,
                message: '请输入数据描述',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '是否可用',
            search: true,
            prop: 'status',
            type: 'switch',
            value: 2,
            dataType: 'number',
            align: 'center',
            dicData: [
              {
                label: '否',
                value: 2
              },
              {
                label: '是',
                value: 1
              }
            ],
            slot: true,
            rules: [
              {
                required: true,
                message: '请选择是否可用',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '主SQL',
            prop: 'querySql',
            type: 'textarea',
            maxRows: 3,
            minRows: 3,
            rules: [
              {
                required: true,
                message: '请输入主SQL',
                trigger: 'blur'
              }
            ]
          }
        ]
      },
      //版本弹出框数据
      editionpage: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      showedition: false, //展示选择dialog
      codeis: '', //展示选择dialog
      editionId: '', //展示选择dialog
      dataedition: [],
      optionedition: {
        height: 500,
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 24,
        searchMenuPosition: 'right',
        menuWidth: 250,
        border: true,
        index: true,
        addBtn: true,
        viewBtn: true,
        viewBtnText: '详情',
        viewTitle: '详情',
        editBtn: true,
        delBtn: true,
        selection: true,
        dialogClickModal: false,
        indexLabel: '序号',
        columnBtn: false,
        column: [
          {
            label: '版本名称',
            prop: 'version',
            search: true,
            rules: [
              {
                required: true,
                message: '请输入版本名称',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '是否启用',
            prop: 'status',
            search: true,
            type: 'switch',
            value: 1,
            dataType: 'number',
            align: 'center',
            dicData: [
              {
                label: '否',
                value: 2
              },
              {
                label: '是',
                value: 1
              }
            ]
          },
          {
            label: '上传缩略图',
            prop: 'thumbnailUrl',
            type: 'upload',
            loadText: '缩略图上传中，请稍等',
            propsHttp: {
              url: 'link',
              name: 'originalName',
              res: 'data'
            },

            listType: 'picture',
            limit: 1,
            accept: 'image/png, image/jpeg, image/jpg',
            tip: '只能上传png/jpeg/jpg文件',
            action: '/api/blade-resource/oss/endpoint/put-file-attach'
          },
          {
            label: '上传打印标签',
            prop: 'fileUrl',
            type: 'upload',
            loadText: '标签上传中，请稍等',
            propsHttp: {
              url: 'link',
              name: 'originalName',
              res: 'data'
            },
            listType: 'text',
            limit: 1,
            accept: '.btw',
            tip: '只能上传btw文件',
            action: '/api/blade-resource/oss/endpoint/put-file-attach',
            rules: [
              {
                required: true,
                message: '请上传打印标签',
                trigger: 'blur'
              }
            ]
          }
        ]
      },
      defaultScmDialog: {
        visible: false,
        option: {
          submitBtn: false,
          emptyBtn: false,
          labelWidth: 120,
          column: [
            {
              label: '默认SCM模板',
              prop: 'labelTemplate',
              type: 'search',
              disabled: true,
              span: 24,
              placeholder: '请选择默认SCM模板',
              rules: [
                {
                  required: true,
                  message: '请选择默认SCM模板',
                  trigger: 'blur'
                }
              ],
              appendClick: () => {
                this.openLabelTemplateModal();
              }
            }
          ]
        },
        form: {}
      },
      modalName: '',
      timer: new Date().getTime()
    };
  },
  mounted() {
    this.$nextTick(() => {
      //搜索与表格结构分隔
      this.$structuralSplit();
    });
  },
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.labeltemplate_add, false),
        viewBtn: this.vaildData(this.permission.labeltemplate_view, false),
        delBtn: this.vaildData(this.permission.labeltemplate_delete, false),
        editBtn: this.vaildData(this.permission.labeltemplate_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(',');
    }
  },
  methods: {
    openPrintLabelModal() {
      this.printLabelModal = true;
      this.dialogTitle = '新增';
      this.form.code = guid().substr(24, 12);
    },
    async getSubTypeData(val) {
      try {
        const res = await getCategory({ code: val });
        this.subTypeList = (res.data.data || []).map((item) => ({
          label: item.dictValue,
          value: item.dictKey
        }));
      } catch (e) {
        console.warn(e);
      }
    },
    rowSave(row, done, loading) {
      add(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          done();
        },
        (error) => {
          loading();
          window.console.log(error);
        }
      );
    },
    rowUpdate(row, index, done, loading) {
      if (row.thumbnailUrl == '') {
        row.thumbnailAttachId = '';
      }
      // 版本管理编辑 取值需要变更
      // row.fileName = this.fileName;
      update(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          done();
        },
        (error) => {
          loading();
        }
      );
    },

    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },
    rowDelEdition(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.geteditionList(this.editionpage, {});
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },
    rowUpdateEdition(row, index, done, loading) {
      console.log(row);
      if (row.thumbnailUrl == '') {
        row.thumbnailAttachId = '';
      }
      // 版本管理编辑 取值需要变更
      // row.fileName = this.fileName;
      addinfo(row).then(
        () => {
          this.geteditionList(this.editionpage, {});
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          done();
        },
        (error) => {
          loading();
        }
      );
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.$refs.crud.toggleSelection();
        });
    },
    //解绑数据源
    dataUnbinding() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据解绑?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return unBindingDataSql(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen(done, type) {
      if (['edit', 'view'].includes(type)) {
        getDetail(this.form.id).then((res) => {
          this.form = res.data.data;
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      params.isLastest = true;
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },
    /**
     *
     * 绑定数据源
     */
    async selectItem(row, title) {
      this.selectionid = row.dataId || '';
      this.dataId = row.dataId;
      this.showCheckDialog = true;
      this.labelTemplateIds = row.id;
      this.onLoadpage(this.itemPage, this.itemQuery);
    },

    currentItemChange(currentPage) {
      this.itemPage.currentPage = currentPage;
      this.onLoadpage(this.itemPage, this.itemQuery);
    },
    sizeItemChange(pageSize) {
      this.itemPage.pageSize = pageSize;
      this.onLoadpage(this.itemPage, this.itemQuery);
    },
    selectionChangeTo(selection, row) {
      if (selection.length > 1) {
        const preVal = selection.shift();
        this.$refs.inspectionProperties.toggleRowSelection(preVal, false);
      }
    },
    searchItemChange(params, done) {
      this.onLoadpage(this.itemPage, params);
      done();
    },
    searchItemReset() {
      this.onLoadpage(this.itemPage);
    },
    rowClick(row) {
      this.selectionid = row.id;
    },
    //数据源分页
    onLoadpage(page, params = {}) {
      // params.status = 1;
      this.loading = true;
      getPage(page.currentPage, page.pageSize, Object.assign(params, this.query, { type: 'LABEL_TEMPLATE' })).then((res) => {
        this.page.total = res.data.data.total;
        this.dataValue = res.data.data.records;
        this.loading = false;
      });
    },
    //数据源绑定
    dataBinding() {
      if (this.dataId && this.dataId !== this.selectionid) {
        this.$confirm('确定修改数据源?', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.handleBandDataSql();
        });
      } else {
        this.handleBandDataSql();
      }
    },
    handleBandDataSql() {
      bindingDataSql(this.labelTemplateIds, this.selectionid).then(
        () => {
          this.labelTemplateIds = '';
          this.selectionid = '';
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.showCheckDialog = false;
          this.onLoad(this.page);
        },
        (error) => {
          loading();
          window.console.log(error);
        }
      );
    },
    /**
     * 更新编码
     */
    updateCode() {
      this.form.code = guid().substr(24, 12);
    },

    onSavePrintLabel() {
      this.$refs.printLabelForm.validate((valid, done) => {
        if (valid) {
          if (this.dialogTitle === '新增') {
            this.form.thumbnailUrl = this._get(this.form, 'thumbnailUrl[0].value', '');
            this.form.fileUrl = this._get(this.form, 'fileUrl[0].value', '');
            add(this.form).then(
              (res) => {
                this.onLoad(this.page);
                this.$message({
                  type: 'success',
                  message: '操作成功!'
                });
                this.printLabelModal = false;
              },
              (error) => {
                window.console.log(error);
              }
            );
            done();
          } else if (this.dialogTitle === '编辑') {
            if (this.form.thumbnailUrl == '') {
              this.form.thumbnailAttachId = '';
            }
            this.form.extFields = null;
            update(this.form).then(
              () => {
                this.onLoad(this.page);
                this.$message({
                  type: 'success',
                  message: '编辑成功!'
                });
                this.printLabelModal = false;
              },
              (error) => {}
            );
            done();
          }
        }
      });
    },
    closeDialog() {
      this.$refs.printLabelForm.resetFields();
      this.form = {};
    },

    async templateApplication(row) {
      this.fileName = row.fileName;
      this.showedition = true;
      this.codeis = row.code;
      this.editionId = row.id;
      let params = {
        code: row.code
      };
      await this.geteditionList(this.editionpage, params);
    },
    geteditionList(editionpage, params) {
      params.code = this.codeis;
      getList(editionpage.currentPage, editionpage.pageSize, Object.assign(params, '')).then((res) => {
        this.editionpage.total = res.data.data.total;
        this.dataedition = res.data.data.records;
      });
    },

    rowSaveEdition(row, done, loading) {
      let params = {
        fileUrl: row.fileUrl[0] ? row.fileUrl[0].value : '',
        // fileName: this.fileName,
        thumbnailUrl: row.thumbnailUrl[0] ? row.thumbnailUrl[0].value : '',
        thumbnailName: row.thumbnailUrl[0] ? row.thumbnailUrl[0].label : '',
        version: row.version || '',
        status: row.status || '',
        labelAttachId: this.form.labelAttachId,
        thumbnailAttachId: this.form.thumbnailAttachId,
        originVersionId: this.editionId
      };
      addinfo(params).then(
        () => {
          this.geteditionList(this.editionpage, {});
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          done();
        },
        (error) => {
          loading();
        }
      );
    },
    refreshChangeTo() {
      this.geteditionList();
    },
    searchChangeTO(params, done) {
      this.editionpage.currentPage = 1;
      this.geteditionList(this.editionpage, params);
      done();
    },
    searchResetTO() {
      this.geteditionList(this.editionpage);
    },
    /**
     * 查看详情数据
     */
    rowView(row) {
      this.printLabelModal = true;
      this.dialogTitle = '查看';
      this.$nextTick(() => {
        this.$refs.printLabelForm.allDisabled = true;
      });
      getDetail(row.id).then((res) => {
        this.form = res.data.data;
      });
    },

    /**
     * 修改物料数据
     */
    openUpdate(row) {
      this.printLabelModal = true;
      this.dialogTitle = '编辑';
      this.$nextTick(() => {
        this.$refs.printLabelForm.allDisabled = false;
      });
      getDetail(row.id).then((res) => {
        this.form = res.data.data;
      });
    },
    // 下载
    openDownload(row) {
      if (row.fileUrl) {
        this.globalStartLoad('文件下载中，请稍后...');
        downloadFileByUrl(row.fileUrl, row.fileName);
        this.globalEndLoad();
      }
    },
    /**
     * 上传前方法
     */
    uploadBefore(file, done, loading, column) {
      if (column.label === '上传打印标签') {
        if (file.name.split('.')[1] != 'btw') {
          this.$message({
            type: 'warning',
            message: '只能上传btw文件！'
          });
          loading();
          return;
        } else {
          done();
        }
      } else {
        if (file.name.split('.')[1] != 'png' && file.name.split('.')[1] != 'jpeg' && file.name.split('.')[1] != 'jpg') {
          this.$message({
            type: 'warning',
            message: '只能上传png/jpeg/jpg文件！'
          });
          loading();
          return;
        } else {
          done();
        }
      }
    },

    /**
     * 上传后方法
     */
    uploadAfter(res, done, loading, column) {
      if (column.prop === 'thumbnailUrl') {
        this.form.thumbnailAttachId = res.attachId;
      } else if (column.prop === 'fileUrl') {
        this.form.labelAttachId = res.attachId;
        // this.form.fileName = res.originalName.split('.')[0];
      }
      done();
    },
    defaultSCM() {
      this.defaultScmDialog.visible = true;
      this.$set(this.defaultScmDialog.form, 'labelTemplateId', '');
      this.$set(this.defaultScmDialog.form, 'labelTemplate', '');
      getScmDefault().then((res) => {
        let data = res.data.data;
        this.$set(this.defaultScmDialog.form, 'labelTemplateId', data.labelTemplateId);
        this.$set(this.defaultScmDialog.form, 'labelTemplate', data.labelTemplate);
      });
    },
    defaultScmDialogSubmit(form, done) {
      console.log(form);
      setDefaultScm(form.labelTemplateId).then(() => {
        this.$message({
          type: 'success',
          message: '操作成功!'
        });
        this.defaultScmDialog.visible = false;
      });
      done();
    },
    openLabelTemplateModal() {
      this.modalName = 'labelTemplateModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择标签模板（双击进行选择）',
        url: '/api/mes-admin/labeltemplate/page?type=MATERIAL&subTypeStr=RAW_MATERIAL_PACKAGING,ACCESSORIES',
        isPage: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '大类',
            prop: 'type',
            type: 'select',
            dicUrl: '/api/blade-system/dict/dictionary?code=dalei',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            }
          },
          {
            label: '小类',
            prop: 'subType',
            type: 'select',
            search: true,
            dicData: [
              { label: '原材料包装', value: 'RAW_MATERIAL_PACKAGING' },
              { label: '辅料', value: 'ACCESSORIES' }
            ]
          },
          {
            label: '模板名称',
            prop: 'fileName',
            search: true
          },
          {
            label: '模板代码',
            prop: 'code',
            search: true
          },
          {
            label: '版本名称',
            prop: 'version'
          },
          {
            label: '缩略图',
            prop: 'thumbnailUrl',
            type: 'upload',
            loadText: '缩略图上传中，请稍等',
            propsHttp: {
              url: 'link',
              name: 'originalName',
              res: 'data'
            },
            listType: 'picture',
            limit: 1,
            accept: 'image/png, image/jpeg, image/jpg',
            tip: '只能上传png/jpeg/jpg文件',
            action: '/api/blade-resource/oss/endpoint/put-file-attach'
          },
          {
            label: '标签地址',
            prop: 'fileUrl',
            overHidden: true
          },
          {
            label: '打印列数',
            prop: 'columnCount'
          },
          {
            label: '打印份数',
            prop: 'copies'
          },
          {
            label: '备注',
            prop: 'remark',
            overHidden: true
          }
        ]
      };
    },
    getSelectedRows(rowData) {
      switch (this.modalName) {
        case 'labelTemplateModal':
          this.$set(this.defaultScmDialog.form, 'labelTemplateId', rowData.id);
          this.$set(this.defaultScmDialog.form, 'labelTemplate', rowData.fileName);
          break;
        default:
          break;
      }
    },
    newKey() {
      this.timer = new Date().getTime();
    }
  }
};
</script>
<style lang="scss" scoped>
::v-deep .el-dialog__header {
  padding: 16px 24px;
  min-height: 20px;
  border-bottom: 1px solid #f0f0f0;
}
::v-deep .el-dialog__footer {
  border-top: 1px solid #f0f0f0;
  padding: 10px 16px;
}

// ::v-deep .el-dialog {
//   .el-dialog__body {
//     .avue-form__menu {
//       display: none;
//     }
//   }
// }
</style>
